package com.example.controller;

import com.example.entity.FileEntity;
import com.example.mapper.FileMapper;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;



@RestController
@RequestMapping("/file")
@Data
@ConfigurationProperties(prefix = "upload")
public class FileController {
    //本地文件目录
    private String uploadDirectory;
    @Autowired
    private FileMapper fileMapper;

    /**
     * 上传文件到本地
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 构建文件保存路径
            Path uploadPath = Paths.get(uploadDirectory, file.getOriginalFilename());
            // 创建目录
            Files.createDirectories(uploadPath.getParent());
            // 将文件保存到磁盘
            Files.copy(file.getInputStream(), uploadPath, StandardCopyOption.REPLACE_EXISTING);

            FileEntity fileEntity = new FileEntity();
            fileEntity.setName(file.getOriginalFilename());
            fileEntity.setLocation("Local");
            fileMapper.insertFile(fileEntity);
            return "File uploaded successfully!";
        } catch (IOException e) {
            return "Error uploading file: " + e.getMessage();
        }
    }

    /**
     * 下载文件
     * @param fileName
     * @return
     * @throws IOException
     */
    @GetMapping("/export")
    public ResponseEntity<Resource> exportFile(@RequestParam("fileName") String fileName) throws IOException {

            // 构建文件路径
            Path filePath = Paths.get(uploadDirectory, fileName);

            // 创建文件资源
            File file = filePath.toFile();
            InputStreamResource resource = new InputStreamResource(Files.newInputStream(file.toPath()));

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"");
            headers.add(HttpHeaders.CONTENT_TYPE, Files.probeContentType(filePath));

            // 返回文件下载响应
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(file.length())
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
        }

}
